package com.example.jiekou;

import com.example.shiti.ProductItemInfo;
import com.example.shiti.TradeInfo;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Repository
public interface SearchOrder extends JpaRepository<TradeInfo, Long> {
    @Query("SELECT t FROM TradeInfo t ORDER BY t.createTime DESC limit 1")
    TradeInfo findLatestCreateTime();

    @Query("SELECT t FROM TradeInfo t ORDER BY t.createTime ASC limit 1")
    TradeInfo findFirstCreateTime();

    @Query("SELECT t FROM TradeInfo t WHERE (:status IS NULL OR t.status = :status) AND t.createTime BETWEEN :startTime AND :endTime")
    List<TradeInfo> findTradeInfoBetweenCreateTimes(
            @Param("status") String status,
            @Param("startTime") Date startTime,
            @Param("endTime") Date endTime,
            @Param("Sort") Sort sort);

    @Query("SELECT t FROM ProductItemInfo t JOIN ProductItemInfo p ON t.tradeInfoId = p.tradeInfoId WHERE p.tradeInfoId IN :tradeInfoIds")
    List<ProductItemInfo> findTradeInfosByTradeInfoIds(@Param("tradeInfoIds") List<String> tradeInfoIds);

    @Query("SELECT COUNT(t) FROM TradeInfo t WHERE (:status IS NULL OR t.status = :status) AND t.createTime BETWEEN :startTime AND :endTime")
    Long countOrdersByStatusAndCreateTimeRange(@Param("status") String status, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

}
